package org.classg.ucenter.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.classg.ucenter.entity.Member;
import org.classg.ucenter.entity.vo.LoginVo;
import org.classg.ucenter.entity.vo.RegisterVo;
import org.classg.ucenter.service.MemberService;
import org.classg.utils.JwtUtils;
import org.classg.utils.R;
import org.classg.vo.UcenterMemberVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-06-04
 */
@RestController
@Api(description = "用户基本功能")
@RequestMapping("/ucenterservice/member")
@CrossOrigin
public class MemberController {

    @Autowired
    private MemberService memberService;

    @ApiOperation("会员登录")
    @PostMapping("/login")
    public R login(@ApiParam(name = "loginVo", value = "用户登录") @RequestBody LoginVo loginVo) {
        String token = memberService.login(loginVo);
        return R.ok().data("token", token);
    }

    @ApiOperation("会员注册")
    @PostMapping("/register")
    public R register(@ApiParam(name = "registerVo", value = "注册封装对象", required = true) @RequestBody RegisterVo registerVo) {
        memberService.register(registerVo);
        return R.ok();
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("/queryUserByToken")
    public R queryUserByToken(@ApiParam(name = "request", value = "请求对象", required = true) HttpServletRequest request) {
        // 调用jwt工具类的方法。根据request对象获取头信息，返回用户id
        String memberIdByJwtToken = JwtUtils.getMemberIdByJwtToken(request);
        // 查询数据库根据用户id获取用户信息
        Member member = memberService.getById(memberIdByJwtToken);
        return R.ok().data("member", member);
    }

    @ApiOperation("根据用户id查询用户信息")
    @GetMapping("/queryUserById/{id}")
    public UcenterMemberVo queryUserById(@ApiParam(name = "id", value = "用户id", required = true) @PathVariable String id) {
        Member member = memberService.getById(id);
        UcenterMemberVo ucenterMemberVo = new UcenterMemberVo();
        BeanUtils.copyProperties(member, ucenterMemberVo);
        return ucenterMemberVo;
    }

    @ApiOperation("根据天数查询注册人数")
    @GetMapping("/queryRegisterCountByDay/{day}")
    public R queryCountByDay(@ApiParam(name = "day", value = "天数", required = true) @PathVariable String day) {
        Integer count = memberService.queryRegisterCountByDay(day);
        return R.ok().data("countPeople", count);
    }

}

